/*
 * @Author: Jason Liu
 * @Date: 2025-06-05 13:19:40
 * @Desc: 
 */

import hdwModule from "../hdwModule";

import scheduleModule from "w-vue-chongqing/src/views/integrationSchedule/inteScheduleDesign/components/scheduleModule";
import transferModule from "w-vue-chongqing/src/views/integrationSchedule/inteScheduleDesign/components/transferModule";

//HDW模型服务
const $modelService = require("w-vue-chongqing/src/api/dataModel");

const $dataIntegration = require("w-vue-chongqing/src/api/dataIntegration");

const $dispatchCenter = require("w-vue-chongqing/src/api/dispatchCenter");

export default {
  components: { ...hdwModule, scheduleModule, transferModule },
  props: {
    value: {
      type: Object,
      default: () => {
        return {
          id: undefined,
          code: undefined,
          name: undefined
        };
      }
    }
  },
  inject: ["updateModelHDWS"],
  data() {
    return {
      loading: false,
      loadingtip: undefined,
      visible: this.show,
      pageKey: 0,

      indicatorInfo: this.value, //指标信息

      hdwList: [], //HDW数据列表
      hdwModule: {
        id: undefined,
        datasourceId: undefined, // 目标数据源id
        schemaName: undefined, // 目标数据源schema
        indicatorCode: undefined, // 指标code
        indicatorName: undefined, // 指标name
        tableId: undefined, // 表id
        tableCode: undefined, // 表code
        tableName: undefined, // 表name
        tableSno: undefined, // 表编码
        sourceDatasourceId: undefined, // 来源数据源id
        sourceSchemaName: undefined, // 来源数据源schema
        sourceTableCode: undefined, // 来源数据源tableCode
        isManual: "1",
        columnList: [],
        indicatorList: []
      },

      jobTaeks: [], //集成调度列表
      activeKey: "jobTask",
      scheduleJob: {},
      modelInfo: {},
      jobInfo: {},
      transferJobs: [],
      targetColumns: [],
      hdwTableEnabled: true,
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.hdwList = [];
      this.jobTaeks = [];
      if (this.indicatorInfo.code) {
        this.getNodeModelByIndicator();
      } else {
        this.addNewModel();
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 
     * @return {*}
     */
    getNodeModelByIndicator() {
      //存在指标编码
      this.loadingtip = "指标模型解析中...";
      this.loading = true;
      const $getHdwData = $modelService.getIndicatorTableData;

      return $getHdwData({
        pageNum: 1,
        pageSize: 10000,
        queryParams: {
          F_isDel_eq: 0,
          F_indicatorCode_like: this.indicatorInfo.code
        }
      })
        .then(req => {
          this.hdwList = (req.data || []).filter(item => {
            if (item.indicatorList && item.indicatorList.length > 0) {
              let has = item.indicatorList.findIndex(inD => {
                return inD.indicatorCode == this.indicatorInfo.code;
              });
              return has > -1;
            } else {
              return false;
            }
          });
          this.updateModelHDWS && this.updateModelHDWS(this.hdwList)
          if (this.hdwList.length > 0) {
            let model = this.hdwList[0];
            return this.queryModeolById(model);
          } else {
            this.loading = false;
            this.addNewModel();
          }
        })
        .finally(() => {
          this.pageKey++;
          this.loading = false;
        });
      // Promise.all([]).finally(() => {
      //   this.loading = false;
      // });
    },
    /**
     * @Author: Jason Liu
     * @description: 根据模型ID信息获取模型
     */
    queryModeolById({ id }) {
      this.loading = true;
      this.loadingtip = "模型详情获取中...";
      return $modelService
        .getIndicatorTableDataById({ id: id })
        .then(hdwreq => {
          this.hdwModule = hdwreq.data;
          this.checkHdwCommonTable(this.hdwModule.tableCode)
          // return this.getDtJobList();
          return this.getHdwInfoByJob();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * @Author: Jason Liu
     * @description: 获取调度信息
     */
    // getDtJobList() {
    //   this.loadingtip = "获取集成调度信息...";
    //   this.loading = true;
    //   const sourceHdw = this.hdwModule;
    //   return $dataIntegration
    //     .getDtJobList({
    //       pageNum: 1,
    //       pageSize: 10000,
    //       queryParams: {
    //         F_jobType_eq: "job",
    //         F_isDel_eq: 0
    //       }
    //     })
    //     .then(req => {
    //       this.jobTaeks = (req.data || []).filter(item => {
    //         let jobTaskDb = item.tableDto;
    //         if (jobTaskDb) {
    //           if (
    //             jobTaskDb.datasourceId == sourceHdw.datasourceId &&
    //             jobTaskDb.tableCode == sourceHdw.tableCode &&
    //             jobTaskDb.schemaName == sourceHdw.schemaName
    //           ) {
    //             return true;
    //           } else {
    //             return false;
    //           }
    //         } else {
    //           return false;
    //         }
    //       });

    //       if (this.jobTaeks.length > 0) {
    //         this.modelInfo = this.jobTaeks[0].tableDto;
    //         this.getHdwInfoByJob(this.jobTaeks[0]);
    //       } else {
    //         this.addNewJobTask();
    //       }
    //     })
    //     .finally(() => {
    //       this.loading = false;
    //     });
    // },
    /**
     * @Author: Jason Liu
     * @description: 根据job信息获取hdw映射信息
     */
    getHdwInfoByJob(value) {
      this.loadingtip = "集成调度解析中...";
      this.loading = true;
      const sourceHdw = this.hdwModule;
      $dataIntegration
        .getHdwTableJob({
          ...sourceHdw
        })
        .then(req => {
          const info = req.data;
          this.targetColumns = this.hdwModule.columnList;
          this.jobInfo = info;
          this.scheduleJob = info.scheduleJob;
          this.transferJobs = info.transferJobs;
          this.modelInfo = info.tableDto;
        })
        .finally(req => {
          this.loading = false;
        });
    },
    /**
     * @Author: Jason Liu
     * @description: 更新模型记录
     */
    updateModelHDWList() {
      $modelService.getIndicatorTableData({
        pageNum: 1,
        pageSize: 10000,
        queryParams: {
          F_isDel_eq: 0,
          F_indicatorCode_like: this.indicatorInfo.code
        }
      }).then(req => {
        let newList = (req.data || []).filter(item => {
          if (item.indicatorList && item.indicatorList.length > 0) {
            let has = item.indicatorList.findIndex(inD => {
              return inD.indicatorCode == this.indicatorInfo.code;
            });
            return has > -1;
          } else {
            return false;
          }
        });
        this.updateModelHDWS && this.updateModelHDWS(newList)
      })
    },
    /**
     * @Author: Jason Liu
     * @description: 设置模型信息
     */
    setMdeol({ key }) {
      if (key == "add") {
        this.addNewModel();
      } else {
        this.queryModeolById({ id: key });
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 获取新映射数据行
     */
    addNewModel() {
      this.hdwTableEnabled = true
      this.hdwModule = {
        id: undefined,
        datasourceId: undefined, // 目标数据源id
        schemaName: undefined, // 目标数据源schema
        indicatorCode: undefined, // 指标code
        indicatorName: undefined, // 指标name
        tableId: undefined, // 表id
        tableCode: undefined, // 表code
        tableName: undefined, // 表name
        tableSno: undefined, // 表编码
        sourceDatasourceId: undefined, // 来源数据源id
        sourceSchemaName: undefined, // 来源数据源schema
        sourceTableCode: undefined, // 来源数据源tableCode
        isManual: "1",
        columnList: [],
        indicatorList: [{
          indicatorCode: this.indicatorInfo.code,
          indicatorName: this.indicatorInfo.name
        }]
      };

      this.addNewJobTask();
    },
    /**
     * @Author: Jason Liu
     * @description: 添加新集成调度
     */

    addNewJobTask() {
      this.modelInfo = {};
      this.jobInfo = {};
      this.transferJobs = [];
      this.targetColumns = [];
      this.$refs.scheduleModule && this.$refs.scheduleModule.initData();
    },
    onClose() {
      this.visible = false;
    },
    /**
     * @Author: Jason Liu
     * @description: 验证作业有效性
     */
    toValidateJobTask(callback) {
      let jobValidate = false;
      this.$refs.transferModule.toValidate(data => {
        jobValidate = data;
      });

      let scheduleValidate = false;
      this.$refs.scheduleModule.toValidate(data => {
        scheduleValidate = data;
      });

      return jobValidate && scheduleValidate
    },
    /**
     * @Author: Jason Liu
     * @description: 一体化集成调度保存
     * @return {*}
     */
    save(callback) {
      // 可能修改了目标表名称，先同步一下modelInfo的数据
      this.modelInfo = { ...this.hdwModule };

      this.loading = true;
      this.loadingtip = "数据有效性验证...";
      let jobTaskFlag = this.toValidateJobTask();
      if (!jobTaskFlag) {
        this.loading = false;
        return false;
      }

      return new Promise((resolve, reject) => {
        this.loadingtip = "HDW模型验证保存中...";
        return $modelService
          .secureSave({ ...this.hdwModule, clusterId: undefined })
          .then(req => {
            this.hdwModule = req.data;
            this.updateModelHDWList();
            this.loadingtip = "字段同步中...";
            $dataIntegration.collectionDataInfo({
              clusterId: this.hdwModule.clusterId,
              collectType: "column",
              dsId: this.hdwModule.datasourceId,
              schema: this.hdwModule.schemaName,
              tableName: this.hdwModule.tableCode
            }).then(req => {
              let columnList = req.data;
              let scheduleParams = this.$refs.scheduleModule.toValidateData();
              let jobParams = this.$refs.transferModule.toValidateData(columnList);

              let params = {
                ...jobParams,
                scheduleJob: scheduleParams,
                tableDto: this.modelInfo
              }
              this.loadingtip = "集成调度保存中...";
              $dataIntegration.saveScheduleTransfer(params)
              .then(req => {
                this.$message.success("集成调度保存成功");
                callback && callback(true);
                // 刷新页面数据
                const newInfo = req.data;
                this.jobInfo = newInfo;
                this.scheduleJob = newInfo.scheduleJob;
                this.transferJobs = newInfo.transferJobs;
                resolve(true);
              })
              .catch(error => {
                this.loading = false;
              });
            }).catch(error => {
              this.loading = false;
            });
          })
          .catch(error => {
            this.$message.error({
              content: error,
              key: "hwdSave"
            });
            this.loading = false;
          });
      }).finally(() => {
        this.loading = false;
      });
    },
    /**
     * @Author: Jason Liu
     * @description: 获取HDW事件
     */
    getHdwData() {},
    /**
     * @Author: Jason Liu
     * @description: 新增HDW数据
     */
    addNewHdw() {},
    /**
     * @Author: Jason Liu
     * @description: 修改数据列事件
     */

    changeColumnList() {
      this.targetColumns = this.hdwModule.columnList;
      this.setJobCol();
      this.pageKey++;
    },
    setJobCol() {
      if (this.transferJobs.length > 0) {
        this.transferJobs.forEach(transfer => {
          transfer.jsonCells.steps.forEach(item => {
            switch (item.data.type) {
              case "TableOutput":
                item.data.columns = this.targetColumns.map(v => {
                  let desc = v.columnName;
                  let name = v.columnCode;
                  return {
                    ...v,
                    description: desc,
                    columnName: name
                  }
                });
                // 更新输出表数据
                item.data.dbId = this.modelInfo.datasourceId;
                item.data.schema = this.modelInfo.schemaName;
                item.data.schemaId = this.modelInfo.schemaName;
                item.data.tableCode = this.modelInfo.tableCode;
                item.data.tableName = this.modelInfo.tableName;

                let tempMapping = JSON.DeepCopy(item.data.mapping);
                item.data.mapping = this.targetColumns.map(v => {
                  let targetIndex = tempMapping.findIndex(old => {
                    return old.target.columnName == v.columnCode;
                  });
                  let source = {
                    pk: false,
                    columnName: undefined,
                    select: undefined,
                    type: "fun",
                    columnType: undefined,
                    description: undefined,
                    columnTypeFlink: undefined,
                    lockType: false
                  };
                  if (targetIndex > -1) {
                    source = tempMapping[targetIndex].source;
                    tempMapping.splice(targetIndex, 1);
                  }

                  let desc = v.columnName;
                  let name = v.columnCode;
                  return {
                    source: {
                      pk: false,
                      columnName: undefined,
                      select: undefined,
                      type: "fun",
                      columnType: undefined,
                      description: undefined,
                      columnTypeFlink: undefined,
                      lockType: false,
                      ...source
                    },
                    target: {
                      ...v,
                      columnName: name,
                      description: desc
                    }
                  };
                });
                break;

              default:
                break;
            }
          });
        });
      }
    },

    setJobData() {
      // 选择来源库，更新关联表
      if (this.transferJobs.length > 0) {
        let isUpdate = false;
        this.transferJobs.forEach((transfer, index) => {
          if(index == 0) {
            transfer.jobName = this.modelInfo.sourceTableCode;
            transfer.jsonCells.steps.forEach(item => {
              if(item.data.type == "TableInput" && !isUpdate) {
                let columnList = this.targetColumns.map(v => {
                  // 数据处理，字段列表里面，columnName对应模型字段里面的columnCode，description对应columnName字段
                  let desc = v.columnName;
                  let name = v.columnCode;
                  return {
                    asName: v.asName || v.columnName,
                    tableAsName: this.modelInfo.sourceTableCode,
                    tableCode: this.modelInfo.sourceTableCode,
                    tableName: this.modelInfo.sourceTableCode,
                    ...v,
                    columnName: name,
                    description: desc
                  }
                })
                item.data = {
                  ...item.data,
                  dbId: this.modelInfo.sourceDatasourceId,
                  schema: this.modelInfo.sourceSchemaName,
                  dbSchema: this.modelInfo.sourceSchemaName,
                  tableCode: this.modelInfo.sourceTableCode,
                  asName: this.modelInfo.sourceTableCode,
                  columns: columnList,
                  isMain: true,
                }
                isUpdate = true;
              }
            });
          }
        });
        this.$refs.transferModule && this.$refs.transferModule.changeTableInfo();
      }
    },
    /**
     * @Author: Jason Liu
     * @description: 修改模型信息
     */
    changeMdeol(model) {
      this.scheduleJob.jobDesc = this.jobInfo.jobName = this.hdwModule.tableCode;

      this.modelInfo = {
        ...this.hdwModule
      };

      this.targetColumns = this.hdwModule.columnList;

      // 校验是否为公版表
      if (model.tableCode) {
        this.checkHdwCommonTable(model.tableCode)
      }

      // 更新来源表数据、目标表数据
      this.setJobCol();
      this.setJobData();

      this.pageKey++;
      this.$forceUpdate();
    },
    /**
     * 校验是否为hdw公版表
     */
    async checkHdwCommonTable(tableCode) {
      const {data} = await $modelService.checkHdwCommonTable({tableCode})
      this.hdwTableEnabled = !data
    },
  },
  watch: {
    value(val) {
      if (val.code != this.indicatorInfo.code) {
        this.init();
      }
      this.indicatorInfo = val;
    },
    indicatorInfo(val) {
      this.$emit("input", val);
    }
  }
};
